package com.fstec.ks.master.dao.jdbc;

import java.util.Date;
import java.util.List;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.fstec.ks.master.dao.ExamRoundDao;
import com.fstec.ks.master.dao.jdbc.extractor.ExamRoundExtractor;
import com.fstec.ks.master.vo.ExamRoundVO;
import com.sinotn.id.SeqUUIDGenerator;
import com.sinotn.spring.jdbc.ParameterSetter;

public class DefaultExamRoundDao extends JdbcDaoSupport implements ExamRoundDao {
	private String schema;
	private String tableName="km_exam_round";

	public void setSchema(String schema) {
		this.schema = schema;
	}
	
	@Override
	public int insert(ExamRoundVO examRoundVO) {
		StringBuilder sb=new StringBuilder();
		sb.append("INSERT INTO ").append(this.schema).append(".").append(this.tableName);
		sb.append(" (").append(ExamRoundExtractor.getColumns()).append(") VALUES (?,?,?)");
		if(examRoundVO.getId()==null){
			examRoundVO.setId(SeqUUIDGenerator.genSequenceUUID(examRoundVO.getBeginTime().getTime()));
		}
		ParameterSetter ps=new ParameterSetter(3);
		ps.set(examRoundVO.getId());
		ps.set(examRoundVO.getBeginTime().getTime());
		ps.set(examRoundVO.getEndTime().getTime());
		return this.getJdbcTemplate().update(sb.toString(), ps);
	}

	@Override
	public ExamRoundVO select(Date beginTime, Date endTime) {
		StringBuilder sb=new StringBuilder();
		sb.append("SELECT ").append(ExamRoundExtractor.getColumns()).append(" FROM ").append(this.schema).append(".").append(this.tableName);
		sb.append(" WHERE begin_time=? AND end_time=?");
		ParameterSetter ps=new ParameterSetter(2);
		ps.set(beginTime.getTime());
		ps.set(endTime.getTime());
		List<ExamRoundVO> list=this.getJdbcTemplate().query(sb.toString(), ps, new ExamRoundExtractor());
		if(list.isEmpty()) return null;
		return list.get(0);
	}

	@Override
	public List<ExamRoundVO> selects() {
		StringBuilder sb=new StringBuilder();
		sb.append("SELECT ").append(ExamRoundExtractor.getColumns());
		sb.append(" FROM ").append(this.schema).append(".").append(this.tableName);

		return this.getJdbcTemplate().query(sb.toString(), new ExamRoundExtractor());
	}
}
